﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.IO;

namespace DLC.Module.DataTable
{
    public partial class BaseMachineEditor : Editor
    {
        protected virtual ScriptPrescription GenerateAsString(BaseMachine m)
        {
            if (m == null)
                return null;

            ScriptPrescription sp = new ScriptPrescription();

            if (m.onlyCreateDataClass)
            {
                CreateDataClassScript(m, sp);
            }
            else
            {
                CreateStringObjectClassScript(m, sp);
                //CreateScriptableObjectEditorClassScript(m, sp);
                CreateDataClassScript(m, sp);
                CreateStringAssetCreationScript(m, sp);
            }

            AssetDatabase.Refresh();

            return sp;
        }
        protected void CreateStringObjectClassScript(BaseMachine m, ScriptPrescription sp)
        {
            sp.NamespaceModuleName = machine.NamespaceModuleName;
            sp.NamespaceGameName = machine.NamespaceGameName;
            sp.className = machine.WorkSheetName;
            sp.dataClassName = machine.WorkSheetName + "Data";
            sp.template = GetTemplate("StringObjectClass");

            // check the directory path exists
            string fullPath = TargetPathForClassScript(machine.WorkSheetName+".String");
            string folderPath = Path.GetDirectoryName(fullPath);
            if (!Directory.Exists(folderPath))
            {
                EditorUtility.DisplayDialog(
                    "Warning",
                    "The folder for runtime script files does not exist. Check the path " + folderPath + " exists.",
                    "OK"
                );
                return;
            }

            StreamWriter writer = null;
            try
            {
                // write a script to the given folder.		
                writer = new StreamWriter(fullPath);
                writer.Write(new ScriptGenerator(sp).ToString());
            }
            catch (System.Exception e)
            {
                Debug.LogError(e.Message);
            }
            finally
            {
                if (writer != null)
                {
                    writer.Close();
                    writer.Dispose();
                }
            }
        }
        protected virtual void CreateStringAssetCreationScript(BaseMachine m, ScriptPrescription sp)
        {
            Debug.LogWarning("!!! It should be implemented in the derived class !!!");
        }
    }
}
